#coding=gbk
#LightCam 

#init by hfh 20150212

import socket,os,time,re,subprocess,traceback,math,sys
import SocketServer,urllib,binascii
import lc_libs


def ChkCpu(host,system):
	if system == "Linux":
		cmd="ssh -n %s \"vmstat |tail -1 |awk '{print \\$(NF-2)}'\"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		idle=popen.stdout.read().strip('\n')
		cpu=100-float(idle)
		return str(cpu)
	elif system == "AIX":
		cmd="ssh -n %s \"vmstat |tail -1 |awk '{print \\$(NF-1)}'\"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		idle=popen.stdout.read().strip('\n')
		cpu=100-float(idle)
		return str(cpu)
	elif system == "HP-UX":
		cmd="ssh -n %s \"vmstat |tail -1 |awk '{print \$NF}'\"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		idle=popen.stdout.read().strip('\n')
		cpu=100 - int(idle)
		return str(cpu)

def ChkMem(host,system):
	if system == "Linux":
		cmd="ssh -n %s \"free \"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		mem_total=0.1
		mem_used=0
		for line in popen.stdout.read().split('\n'):
			if "Mem" in line:
				mem_total=line.split()[1]
			elif "buffers/cache" in line:
				mem_used=line.split()[2]
		used=float(mem_used)*100/float(mem_total)
		used=round(used,2)
		return str(used)
	elif system == "AIX":
		cmd="ssh -n %s \"svmon -G \"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		mem_total=0.1
		mem_used=0
		for line in popen.stdout.read().split('\n'):
			if "memory" in line:
				mem_total=line.split()[1]
				mem_used=line.split()[2]
		used=float(mem_used)*100/float(mem_total)
		used=round(used,2)
		return str(used)
	elif system == "HP-UX":
		cmd="ssh -n %s \"/usr/sbin/swapinfo |tail -1 |awk '{print \$3*100/\$2}'\"" % host
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		used=popen.stdout.read().strip('\n')
		print used
		used=round(float(used),2)
		return str(used)


def ChkDisk(host,name):
	cmd="ssh -n %s \"df -P|grep %s\$|awk '{print \$(NF-1)}'\"" % (host,name)
	print cmd
	popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	time.sleep(1)
	used=popen.stdout.read().strip('\n').strip('%')
	print " %s :-----%s-----" % (cmd,used)
	used=round(float(used),2)
	return str(used)


def ChkAllDisk(host):
	MaxDiskName=""
	MaxDiskUsedPercent=0
	#cmd="ssh %s \"df -P|grep \"/\$\"|awk '{print \$NF\\\" \\\"\$(NF-1)}'\"" % (host)
	cmd="ssh -n %s \"df -P\"" % host
	print cmd
	popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	time.sleep(1)
	res=popen.stdout.read().strip('\r\n ')
	print res
	for line in res.split('\n'):
		lines=line.split()
		if len(lines)<2 or "/" not in line:
			continue
		DiskName=lines[-1]
		DiskUsedPercent=float(lines[-2].strip('%'))
		if MaxDiskUsedPercent < DiskUsedPercent:
			MaxDiskUsedPercent=DiskUsedPercent
			MaxDiskName=DiskName
	res=str(MaxDiskUsedPercent)+"__"+MaxDiskName
	return res
	
	used=popen.stdout.read().strip('\n').strip('%')
	print " %s :-----%s-----" % (cmd,used)
	used=round(float(used),2)
	return str(used)
	
	
def ChkProcess(host,name):
	num=0
	cmd="ssh -n %s \"ps -ef|grep -w \\\"%s\\\"|grep -v grep|wc -l\"" % (host,name)
	popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	num=popen.stdout.read().strip('\r\n')
	return str(num)
	
	
def ChkTcpLink(host,portname,porttype,portsite):
	num=0
	cmd="ssh -n %s \"netstat -an|grep %s\"" % (host,porttype)
	popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	time.sleep(0.1)
	for line in popen.stdout.read().split('\n'):
		if ":" not in line:
			continue
		if portsite=="local" and portname == line.split()[3].split(':')[-1]:
			num=num+1
		elif portsite=="peer" and portname == line.split()[4].split(':')[-1]:
			num=num+1
	return str(num)
	
	
def ChkURL(url):
	try:
		urllib.urlopen(url)
		return 1
	except IOError:
		return 0
	
def ChkRPing(system,ping_count,ping_interval,ping_timeout,ipaddr):
	percent=''
	if system == "Linux":
		cmd="ping -c %s -i %s -W %s %s|grep transmitted" % (ping_count,ping_interval,ping_timeout,ipaddr)
		print cmd
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		res=popen.stdout.read().strip('\r\n ')
		for line in res:
			if "packet loss" not in res:
				percent = 'unknow'
			else:
				percent = res.split(',')[2].split()[0].strip('%').strip('')
	elif system == "AIX":
		cmd="ping -c %s -i %s -w %s %s|grep transmitted" % (ping_count,ping_interval,ping_timeout,ipaddr)
		print cmd
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		res=popen.stdout.read().strip('\r\n ')
		for line in res:
			if "packet loss" not in res:
				percent = 'unknow'
			else:
				percent = res.split(',')[2].split()[0].strip('%').strip('')
	elif system == "HP-UX":
		cmd="ping -I %s %s -n %s -m %s|grep transmitted" % (ping_interval,ipaddr,ping_count,ping_timeout)
		print cmd
		popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		res=popen.stdout.read().strip('\r\n ')
		for line in res:
			if "packet loss" not in res:
				percent = 'unknow'
			else:
				percent = res.split(',')[2].split()[0].strip('%').strip('')
	return str(percent)
	
def ChkCRC(filename):
	CRC = binascii.crc32(open(filename).read())
	return CRC
	
def ChkNTP(ntpsvr):
	c = ntplib.NTPClient()
	try:
		response = c.request(ntpsvr)
	except Exception:
		excinfo=traceback.format_exc()
		return 1
		exit(0)
	return 0

def ChkBreaker(hostname):
	cmd="ssh -n %s \"grep -c ReportFuseEvent /cffex/trade/%s/bin/Syslog.log\"" % (hostname,hostname)
	popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	res=popen.stdout.read().strip('\r\n')+popen.stderr.read().strip('\r\n')
	if "No such file" in res:
		return "NoSuchFile"
	if int(res)>0:
		return "Breaker"
	else:
		return "OK"
	
class LCAgent(SocketServer.StreamRequestHandler):
	def handle(self):
		while True:
			sd=""
			try:
				buf=self.request.recv(1024)
				if re.match("__StartOfTheCommand__",buf):
					self.request.sendall('__ReadyForTheCommand__')
				else:
					sd=sd+buf
					if re.match(".*__EndOfTheCommand__",sd):
						cmd=sd.replace("__EndOfTheCommand__","")
						logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
						print logdate+" CMD:"+str(cmd)
						#logfile.write(logdate+" CMD:"+str(cmd)+"\n")
						#logfile.flush()
						line=""
						try:
							if "ChkCpu" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								system=exprs[2]
								line=ChkCpu(host,system)
							elif "ChkMem" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								system=exprs[2]
								line=ChkMem(host,system)
							elif "ChkDisk" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								name=exprs[2]
								line=ChkDisk(host,name)
							elif "ChkAllDisk" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								name=exprs[2]
								line=ChkAllDisk(host)
							elif "ChkProcess" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								name=exprs[2]
								line=ChkProcess(host,name)
							elif "ChkTcpLink" in str(cmd):
								exprs=cmd.split('__')
								host=exprs[1]
								portname=exprs[2]
								porttype=exprs[3]
								portsite=exprs[4]
								line=ChkTcpLink(host,portname,porttype,portsite)
							elif "ChkURL" in str(cmd):
								exprs=cmd.split('_')
								url=exprs[1]
								line=ChkURL(url)
							elif "ChkRPing" in str(cmd):
								exprs=cmd.split('__')
								ipaddr=exprs[1]
								ping_count=exprs[2]
								ping_interval=exprs[3]
								ping_timeout=exprs[4]
								system=exprs[5]
								line=ChkRPing(system,ping_count,ping_interval,ping_timeout,ipaddr)
							elif "ChkCRC" in str(cmd):
								exprs=cmd.split('_')
								filename=exprs[1]
								line=ChkCRC(filename)
							elif "ChkNTP" in str(cmd):
								exprs=cmd.split('_')
								ntpsvr=exprs[1]
								line=ChkNTP(ntpsvr)
							elif "ChkBreaker" in str(cmd):
								exprs=cmd.split('__')
								hostname=exprs[1]
								line=ChkBreaker(hostname)
							else:
								popen=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
								line=popen.stdout.read()
							#logdate=time.strftime('%b %d %H:%M:%S',time.localtime())
							#print logdate+" "+line
							#logfile.write(logdate+" "+line+"\n")
						except Exception:
							excinfo=traceback.format_exc()
							print excinfo
							logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
							logfile.write(logdate+" CMD:"+cmd+"\n")
							logfile.write(logdate+" "+excinfo+"\n")
							logfile.flush()
							line="1234567890"
						print line
						self.request.sendall(str(line)+"__EndOfTheResult__")
						break
					else:
						#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
						#logfile.write(logdate+" illeagle connection \n")
						#logfile.flush()
						break
			except Exception:
				excinfo=traceback.format_exc()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				logfile.write(logdate+" CMD:"+cmd+"\n")
				logfile.write(logdate+" "+excinfo+"\n")
				logfile.flush()
			time.sleep(0.1)
		time.sleep(0.1)


if __name__ == "__main__":

	cmd='echo $LIGHTCAM_HOME'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	while True:
		if popen.poll()==None:
			time.sleep(0.1)
			continue
		else:
			break
	lchome=popen.stdout.read().strip('\r\n')
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	#LocalIP="0.0.0.0"
	#LocalPort=1055

	ADDR=("0.0.0.0",1066)
	
	try:
		server = SocketServer.ThreadingTCPServer(ADDR,LCAgent)
		server.serve_forever()

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" "+excinfo+"\n")
		logfile.flush()
		server.shutdown()
		exit(0)
		#os.system('. ~/.profile;lc_stop AgentHM')
